package day05;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;

/**
 * Flink Table API 与 SQL —— 输出到文件
 *
 * @author lvbingbing
 * @date 2022-01-13 21:56
 */
public class FlinkTableApi02 {
    public static void main(String[] args) throws Exception {
        // 1、获取可执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        int parallelism = 1;
        env.setParallelism(parallelism);
        // 2、输出到文件
        studyWriteToFile(env);
        // 3、触发程序执行
        env.execute();
    }

    /**
     * 输出到文件
     *
     * @param env <br>
     */
    private static void studyWriteToFile(StreamExecutionEnvironment env) {
        // 1、创建表环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 2、连接外部系统，读取数据
        String path = "input/sensor.txt";
        tableEnv.connect(new FileSystem().path(path))
                .withFormat(new Csv())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("timestamp", DataTypes.BIGINT())
                        .field("temp", DataTypes.DOUBLE()))
                .createTemporaryTable("inputTable");
        // 3、查询转换
        // 3.1 Table API
        Table inputTable = tableEnv.from("inputTable");
        Table resTable = inputTable.select("id, temp")
                .filter("id === 'sensor_6'");
        // 聚合统计
        Table aggTable = inputTable.groupBy("id")
                .select("id, id.count as cnt, temp.avg as avgTemp");
        // 3.2 SQL
        Table sqlQueryTable = tableEnv.sqlQuery("select id, temp from inputTable where id = 'sensor_6'");
        Table avgSqlQueryTable = tableEnv.sqlQuery("select id, count(id) as cnt, avg(temp) as avgTemp from inputTable group by id");

        // 4、输出到文件
        String outputPath = "output/output.txt";
        tableEnv.connect(new FileSystem().path(outputPath))
                .withFormat(new Csv())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("temperature", DataTypes.DOUBLE()))
                .createTemporaryTable("outputTable");

         resTable.insertInto("outputTable");
    }
}